
//
//  QRCodeScanningViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/26.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit

class QRCodeScanningViewController: BaseViewController, SGQRCodeScanManagerDelegate, SGQRCodeAlbumManagerDelegate {
    
    var scanningView: SGQRCodeScanningView? = nil
    let manager = SGQRCodeScanManager.shared()
    
    func rightBarButtonItenAction() {
        let manager = SGQRCodeAlbumManager.shared()
        manager?.sg_readQRCodeFromAlbum(withCurrentController: self)
        manager?.delegate = self
        DispatchQueue.global().async(qos: .default, flags: .barrier) {
            let isPHAuthorization = manager?.isPHAuthorization
            if isPHAuthorization! {
                DispatchQueue.main.async {
                    self.removeScanningView()
                }
            }
        }
    }
    
    func setupQRCodeScanning() {
        let arr = [AVMetadataObject.ObjectType.qr, AVMetadataObject.ObjectType.ean13, AVMetadataObject.ObjectType.ean8, AVMetadataObject.ObjectType.code128]
        manager?.sg_setupSessionPreset(AVCaptureSession.Preset.hd1920x1080.rawValue, metadataObjectTypes: arr, currentController: self)
        manager?.delegate = self
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        scanningView?.addTimer()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    deinit {
        removeScanningView()
    }
    
    func removeScanningView() {
        scanningView?.removeTimer()
        scanningView?.removeFromSuperview()
        scanningView = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.clear
        self.automaticallyAdjustsScrollViewInsets = false;
        if scanningView == nil {
            scanningView = SGQRCodeScanningView(frame: view.bounds, layer: view.layer)
        }
        view.addSubview(scanningView!)
        self.setupQRCodeScanning()
        setHideButton()
        // Do any additional setup after loading the view.
    }
    
    func setHideButton() {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "btn_delete"), for: .normal)
        button.addTarget(self, action: #selector(dissmis), for: .touchUpInside)
        view.addSubview(button)
        button.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left)
            make.top.equalTo(view.top).offset(11)
            make.size.equalTo(CGSize(width: 50, height: 50))
        }
    }

    @objc func dissmis() {
        manager?.sg_stopRunning()
        manager?.sg_videoPreviewLayerRemoveFromSuperlayer()
        navigationController?.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - SGQRCodeAlbumManagerDelegate
    func qrCodeAlbumManagerDidCancel(withImagePickerController albumManager: SGQRCodeAlbumManager!) {
        if scanningView == nil {
            scanningView = SGQRCodeScanningView(frame: view.bounds, layer: view.layer)
        }
        view.addSubview(scanningView!)
    }
    
    func qrCodeAlbumManager(_ albumManager: SGQRCodeAlbumManager!, didFinishPickingMediaWithResult result: String!) {
        
    }
    
    func qrCodeScanManager(_ scanManager: SGQRCodeScanManager!, didOutputMetadataObjects metadataObjects: [Any]!) {
        if !metadataObjects.isEmpty {
            let obj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
            let url = obj?.stringValue
            let contents = url?.components(separatedBy: "/")
            // 这个地方和后台对一下
            if contents?.last == "liangpin" {
                scanManager.sg_palySoundName("SGQRCode.bundle/sound.caf")
                scanManager.sg_stopRunning()
                scanManager.sg_videoPreviewLayerRemoveFromSuperlayer()
            }
        } else {
            print("暂未识别出扫描的二维码")
        }
    }
}
